import { ref, computed } from 'vue';
/**
 * @des 高级搜索compositionApi
 * @param fields 表单列表
 * @param saveDataToStorage 保存缓存的方法
 * @param getLocalStorageData 获取缓存的方法
 * @param popperAdvancedSearchDom 高级搜索dom
 * @param handleSearch 搜索方法
 * @returns 
 */
export const useAdvancedSearchState = (fields: any, saveDataToStorage = null, getLocalStorageData:any = null, popperAdvancedSearchDom = null, handleSearch, filterSearchModel = null) => {
  const storageKey = 'advanced-search-commonUse';
  const searchFieldInfo = computed(() => fields.value);

  const conditionParams = ref({});
  function initConditionParams() {
    conditionParams.value = {
      conditions: [],
      systemConditions: [],
    };
  }

  // 搜索所用参数
  initConditionParams();
  // 视图参数
  const viewportSearchModel = ref([]);
  function handleAdvancedSearch(searchModel) {
    conditionParams.value = filterSearchModel ? filterSearchModel(searchModel) : searchModel;
    handleSearch();
  }

  /**
   * 恢复常用字段
   */
  async function recoverCommonUse() {
    try {
      const data = getLocalStorageData ? await getLocalStorageData() : {};
      inCommonUse.value = data[storageKey] || [];
    } catch (error) {
      console.error('获取常用字段 recoverCommonUse', error);
      return Promise.reject(error);
    }
  }
  // 常用条件
  const inCommonUse = ref([]);
  // 设置常用条件
  function changeCommonUse({ fieldName, isChecked }) {
    const inCommonUseSet = new Set(inCommonUse.value);
    if (isChecked) {
      inCommonUseSet.add(fieldName);
    } else {
      inCommonUseSet.delete(fieldName);
    }
    inCommonUse.value = Array.from(inCommonUseSet);
    saveDataToStorage && saveDataToStorage(storageKey, inCommonUse.value);
  }

  // 重置高级搜索条件
  function resetAdvancedConditions() {
    initConditionParams();
    popperAdvancedSearchDom?.value.setButtonStatus(false);
  }
  return {
    searchFieldInfo,
    viewportSearchModel,
    handleAdvancedSearch,
    changeCommonUse,
    inCommonUse,
    resetAdvancedConditions,
    conditionParams,
    recoverCommonUse,
  };
};
